<template>
  <div class="app-container">
    <div class="filter-container">
        <el-input clearable v-model="search.keName" placeholder="课程名称" style="width: 170px;"></el-input>
        <el-input clearable v-model="search.shopName" placeholder="店铺" style="width: 170px;margin-left:5px;"></el-input>
        <el-select v-model="search.keKindOneId" clearable placeholder="大类" @change="changeKindOne" style="width: 130px; margin-left:5px;">
            <el-option 
            v-for="(item,index) in selectOptions.one"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
        <el-select v-model="search.keKindTwoId" clearable placeholder="二类"  @change="changeKindTwo"  style="width: 130px; margin-left:5px;">
            <el-option 
            v-for="(item,index) in selectOptions.two"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
        <el-select v-model="search.keKindThreeId" clearable placeholder="小类"  @change="changeKindThree" style="width: 130px; margin-left:5px;">
            <el-option 
            v-for="(item,index) in selectOptions.three"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select>
        <!-- <el-select v-model="search.isOpen" clearable placeholder="状态" style="width: 130px; margin-left:5px;">
            <el-option 
            v-for="(item,index) in selectOptions.isOpen"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select> -->
        <el-button type="primary" icon="el-icon-search" @click="searchClick()" style="margin-left:10px;">查询</el-button>

    </div>
    <el-table v-loading="listLoading" :data="list" 
      border fit highlight-current-row stripe 
      style="width: 100%">
      <el-table-column align="center" label="序" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row._id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="10%" align="center" label="封面">
        <template slot-scope="scope">
          <span><el-image :src="scope.row.imageConvert" style="width:50px;height:50px" ></el-image> </span>
        </template>
      </el-table-column>

      <el-table-column min-width="15%" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="15%" align="center" label="店铺">
        <template slot-scope="scope">
          <span>{{ scope.row.shopName }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="10%" label="课程分类">
        <template slot-scope="scope">
            <span>{{scope.row.courseThreeType}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="课程编制">
        <template slot-scope="scope">
            <span>{{scope.row.classZhi}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="教师">
        <template slot-scope="scope">
            <span>{{scope.row.courseTeachers}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="课程费用">
        <template slot-scope="scope">
            <span>{{scope.row.price.toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="学习方式">
        <template slot-scope="scope">
            <span>{{scope.row.learnType}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" label="可否试听">
        <template slot-scope="scope">
            <span>{{(scope.row.isAssembel?'可试听':'否')}}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" min-width="10%">
        <template slot-scope="{row}">
          <el-tag :type="row.isOpen | statusFilter">
            {{ (row.isOpen?'正常':'下架') }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- <el-table-column min-width="300px" label="Title">
        <template slot-scope="{row}">
          <router-link :to="'/example/edit/'+row.id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
        </template>
      </el-table-column> -->
      <el-table-column min-width="10%" align="center" label="时间">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="15%">
        <template slot-scope="scope">
          <router-link :to="'/shopmanage/coursedetails/'+scope.row.id">
            <el-button type="primary" size="small">
              详情
            </el-button>
          </router-link>
          <el-popconfirm :title="'确定要'+(scope.row.isOpen?'下架':'上架')+'这个课程吗？'" icon="el-icon-info"  icon-color="red"  @onConfirm="saveOpenState(scope.row.id,!scope.row.isOpen)" >
              <el-button :type="(scope.row.isOpen?'danger':'success')" size="small" slot="reference" style="margin-left:5px;">
                {{(scope.row.isOpen?'下架':'上架')}}
              </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.rows" @pagination="getList" />
  </div>
</template>

<script>
import * as shopApi from '@/api/shop'
import * as courseApi from '@/api/courseinfo'
import * as kekindApi from '@/api/kekind'
import * as imageHelper from '@/utils/image'
import {deepClone} from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'CourseListShop',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      
      const statusMap=['info','success'];
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        rows: 20,
        state:-1,
        kindOneId:'',
        kindTwoId:'',
        kindThreeId:''
      },
      threetypes:{
        one:[],
        two:[],
        three:[]
      },
      teachers:[],
      search:{
        keName:'',
        shopName:'',
        keKindOneId:'',
        keKindTwoId:'',
        keKindThreeId:'',
        isOpen:''
      },
      selectOptions:{
        one:[
          
        ],
        two:[
          
        ],
        three:[
          
        ],
        isOpen:[
          { label: "正常", value: "true" },
          { label: "下架", value: "false" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {  
    getList() {
      this.listLoading = true;

      courseApi.getCourseList(this.listQuery).then(res => {
          
          var data=res.data.items.map((item,itemidx)=>{
          item.imageConvert=imageHelper.GetFullUrl(item.image,200,200);
          item.courseThreeType='...';
          item.courseTeachers='';
          item.learnType=item.isSuiDaoSuiXue?'随到随学':item.timeInterval;
          item._id=((this.listQuery.page-1)*this.listQuery.rows)+(itemidx+1)
          return item;
        })
        this.list = data;
        this.total = res.data.total; 
        this.listLoading = false;

        //获取课程分类
        
        var that=this;
        recursionFunc(0);

        function recursionFunc(idx){
            var nextitem=that.list[idx];
            if(!nextitem){return;}
            that.getCourseThreeTypes(that,idx,nextitem.keKindOneId,nextitem.keKindTwoId,nextitem.keKindThreeId,function(idxback,typesName){
                var current=that.list[idxback];
                current.courseThreeType=typesName;
                that.$set(that.list,idxback, current);
                recursionFunc(idxback+1);
            });
            
        }
        //==end 获取课程分类

        //获取教师
        if(that.teachers.length==0){
          shopApi.getTeacherList().then(res=>{
              if(res.data &&res.data.items){
                that.teachers.push(...res.data.items);
                convertTeacherName();
              }
          });
        }else{
          convertTeacherName();
        }

        function convertTeacherName(){
           for(var i=0;i<that.list.length;i++){
             var tfilter=that.teachers.filter(item=>{return  that.list[i].teacherIds!=null && that.list[i].teacherIds.indexOf(item.id)>-1;});
             if(tfilter.length>0){
                var current=that.list[i];
                current.courseTeachers=tfilter.map(tc=>{return tc.name}).join(',');
                that.$set(that.list,i, current);
             }
           }
        }

        //==end 获取教师

      })
    },
    getCourseThreeTypes(that,index,oneid,twoid,threeid,callback){
        var success=false;
        var kindNameTogether=[];
        var kindNameOne=getkindname(that.threetypes.one,oneid);

        if(kindNameOne){
           kindNameTogether.push(kindNameOne);
          
          //尝试本地读取二级，不存在则接口读取
          var kindNameTwo=getkindname(that.threetypes.two,twoid);
          if(kindNameTwo){
              kindNameTogether.push(kindNameTwo);

              var kindNameThree=getkindname(that.threetypes.three,threeid);
              if(kindNameThree){
                kindNameTogether.push(kindNameThree);
                callback(index,kindNameTogether.join(','));
              }else{
                //获取三级分类
                kekindApi.getKindList3({upId:twoid,page:1,rows:20}).then(res3=>{
                    if(res3.data){
                        tryaddkinds(that.threetypes.three,res3.data.items);
                        var kindNameThree=getkindname(that.threetypes.three,threeid);
                        kindNameTogether.push(kindNameThree);
                        callback(index,kindNameTogether.join(','));
                    }
                });
              }

          }else{
             //获取二级分类
            kekindApi.getKindList2({upId:oneid,page:1,rows:20}).then(res2=>{
                if(res2.data){
                    tryaddkinds(that.threetypes.two,res2.data.items);
                    var kindNameTwo=getkindname(that.threetypes.two,twoid);
                    kindNameTogether.push(kindNameTwo);
                }

                //获取三级分类
                kekindApi.getKindList3({upId:twoid,page:1,rows:20}).then(res3=>{
                    if(res3.data){
                        tryaddkinds(that.threetypes.three,res3.data.items);
                        var kindNameThree=getkindname(that.threetypes.three,threeid);
                        kindNameTogether.push(kindNameThree);
                        callback(index,kindNameTogether.join(','));
                    }
                });
            });
          }

        }else{
          //一级不存在，则获取一级分类 二级，三级也同样不存在
          kekindApi.getKindList1({page:1,rows:20}).then(res=>{
            if(res.data){
                tryaddkinds(that.threetypes.one,res.data.items);
                kindNameOne=getkindname(that.threetypes.one,oneid);
                kindNameTogether.push(kindNameOne);
                //下拉菜单
                that.selectOptions.one=[...res.data.items.map(item=>{
                  return {label:item.kindName,value:item.id};
                })]
            }
            //获取二级分类
            kekindApi.getKindList2({upId:oneid,page:1,rows:20}).then(res2=>{
                if(res2.data){
                    tryaddkinds(that.threetypes.two,res2.data.items);
                    var kindNameTwo=getkindname(that.threetypes.two,twoid);
                    kindNameTogether.push(kindNameTwo);
                }

                //获取三级分类
                kekindApi.getKindList3({upId:twoid,page:1,rows:20}).then(res3=>{
                    if(res3.data){
                        tryaddkinds(that.threetypes.three,res3.data.items);
                        var kindNameThree=getkindname(that.threetypes.three,threeid);
                        kindNameTogether.push(kindNameThree);
                        callback(index,kindNameTogether.join(','));
                    }
                });
            });
          })
        }

        


        function tryaddkinds(currentKinds,newKindArr){
          if(!currentKinds || !newKindArr){return;}
            for(var i=0;i<newKindArr.length;i++){
                var checkfilter=currentKinds.filter(item=>{return item.id==newKindArr[i].id});
                if(checkfilter.length==0){
                  currentKinds.push(deepClone(newKindArr[i]));
                }
            }
        }

        function getkindname(kinds,kindid){
          if(!kinds){return '';}
           var findfilter=kinds.filter(item=>{return item.id==kindid});
           if(findfilter.length>0){return findfilter[0].kindName;}
           return '';
        }
    },
    searchClick(){
        this.listQuery.page=1;
        this.listQuery.name=this.search.keName.trim();
        this.listQuery.shopName=this.search.shopName.trim();
        this.listQuery.state=this.search.isOpen?(this.search.isOpen=='true'?1:0):'-1';
        this.listQuery.kindOneId=this.search.keKindOneId;
        this.listQuery.kindTwoId=this.search.keKindTwoId;
        this.listQuery.kindThreeId=this.search.keKindThreeId;
        this.getList();
    },

    //课程上下架
    saveOpenState(id,state){
      var that=this;
      courseApi.setCourseOpenState({id:id,isopen:state}).then(res=>{
        if(res.data){
            var idx=that.list.findIndex(item=>item.id==id);
            if(idx>-1){
              var obj=that.list[idx];
              that.list[idx].isOpen=state;
            }
            that.$message({
              message: '保存成功！',
              type: 'success'
            });
        }
      })
    },
    changeKindOne(){
      var that=this;
      that.search.keKindThreeId='';
      that.search.keKindTwoId='';
      if(!that.search.keKindOneId){return;}
       //尝试读取本地的二级分类
       var twos=that.threetypes.two.filter(u=>u.upKindId==that.search.keKindOneId);
       if(twos.length>0){
          that.selectOptions.two=[...twos.map(item=>{
            return {label:item.kindName,value:item.id};
          })]
       }else{
          kekindApi.getKindList2({upId:that.search.keKindOneId}).then(res2=>{
                if(res2.data){
                    that.selectOptions.two=[...res2.data.items.map(item=>{
                      return {label:item.kindName,value:item.id};
                    })];
                    that.threetypes.two=that.threetypes.two.concat(res2.data);
                }
          });
       }
    },
    changeKindTwo(){
      var that=this;
      
      if(!that.search.keKindTwoId){return;}
      that.search.keKindThreeId='';
      that.selectOptions.three.splice(0,that.selectOptions.three.length);
       //尝试读取本地的二级分类
       var threes=that.threetypes.three.filter(u=>u.upKindId==that.search.keKindTwoId);
       if(threes.length>0){
         
          threes.map(item=>{
            that.selectOptions.three.push({label:item.kindName,value:item.id});
          })
       }else{
          kekindApi.getKindList3({upId:that.search.keKindTwoId}).then(res3=>{
                if(res3.data){
                    res3.data.items.map(item=>{
                      that.selectOptions.three.push({label:item.kindName,value:item.id});
                    })
                    that.threetypes.three=that.threetypes.three.concat(res3.data);
                }
          });
       }
    },
    changeKindThree(){
      //如果不强制渲染，这个老是选不中
      this.$forceUpdate();
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}

 
</style>
